#include "tcp_connection.h"
#include "net_context.h"

using namespace usnet;

#ifndef NATIVE_SOCKET
TCPConnection::~TCPConnection()
{
    auto ctx = NetContext::GetContext();
    if (fd_ >= 0) {
        ctx->PutConnFD(fd_);
    }
    tcp_impl_.reset(nullptr);
}

std::unique_ptr<TCPConnection>
TCPConnection::MakeUnique(EndpointAddr* laddr, const EndpointAddr& raddr, const int64_t isn)
{
    auto ctx = NetContext::GetContext();
    std::unique_ptr<TCPConnection> conn { new(std::nothrow) TCPConnection { laddr, raddr, isn } };
    if (conn == nullptr) {
        LOG_ERROR(ctx, "failed to new TCPConnection instance");
        return nullptr;
    }
    conn->fd_ = ctx->GetConnFD();
    if (conn->fd_ < 0) {
        LOG_ERROR(ctx, "failed to allocate fd");
        return nullptr;
    }
    if (conn->InitTCPImpl() == false) {
        LOG_ERROR(ctx, "failed to init TCPImpl");
        return nullptr;
    }
    return conn;
}
#else
TCPConnection::~TCPConnection()
{
    if (fd_ >= 0 ) {
        close(fd_);
        fd_ = -1;
    }
    laddr_ = nullptr;
}

std::unique_ptr<TCPConnection>
TCPConnection::MakeUnique(EndpointAddr* laddr, const EndpointAddr& raddr, const int& connfd)
{
    auto ctx = NetContext::GetContext();
    std::unique_ptr<TCPConnection> conn { new(std::nothrow) TCPConnection { laddr, raddr, connfd } };
    if (conn == nullptr) {
        LOG_ERROR(ctx, "failed to new TCPConnection instance");
        return nullptr;
    }
    return conn;
}
#endif